package com.sevennotes.classtable.utils

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import android.content.pm.PackageManager.PackageInfoFlags
import android.net.Uri
import android.os.Build
import android.util.Log
import android.webkit.MimeTypeMap
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.compose.material3.contentColorFor
import androidx.core.content.FileProvider
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Locale

object CommonUtils {

  private const val PACKAGE_WECHAT = "com.tencent.mm"

  fun getFileExtension(context: Context, uri: Uri): String {
    var contentResolver = context.contentResolver
    var mimeTypeMap = MimeTypeMap.getSingleton()
    var mimeType = contentResolver.getType(uri)
    var extention = mimeTypeMap.getExtensionFromMimeType(mimeType)
    return extention ?: ""
  }

  fun generateFileNameWithDate(prefix: String, extension: String): String {
    val currentDate = Calendar.getInstance().time
    val formatter = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
    val formattedDate = formatter.format(currentDate)
    return "$prefix$formattedDate.$extension"
  }

  suspend fun shareWechatFriend(context: Context, file: File) {
    if (file.extension != "xlsx") {
      withContext(Dispatchers.Main) {
        Toast.makeText(context, "Only support xlsx file", Toast.LENGTH_SHORT).show()
      }
      return
    }
    if (!isInstallApp(context, PACKAGE_WECHAT)) {
      withContext(Dispatchers.Main) {
        Toast.makeText(context, "未安装微信", Toast.LENGTH_SHORT).show()
      }
      return
    }
    try {
      val intent = Intent().apply {
        setPackage(PACKAGE_WECHAT)
        action = Intent.ACTION_SEND
        type = "application/vnd.ms-excel"
        var uri: Uri? = null
        uri =
          if (context.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(
              context,
              "${context.applicationContext.packageName}.fileprovider",
              file
            )
          } else {
            Uri.fromFile(file)
          }
        putExtra(Intent.EXTRA_STREAM, uri)
        flags = Intent.FLAG_ACTIVITY_NEW_TASK
      }
      context.startActivity(Intent.createChooser(intent, "分享文件"))
    } catch (e: Exception) {
      e.printStackTrace()
    }
  }

  private fun isInstallApp(context: Context, appname: String): Boolean {
    val packageManager = context.packageManager
    try {
      val pinfo = packageManager.getInstalledPackages(0)
      pinfo.forEach {
        Log.d("test", "packageName: ${it.packageName}")
        if (it.packageName == appname) {
          return true
        }
      }

      return false
    } catch (e: NameNotFoundException) {
      return false
    }
  }
}